from rest_framework import serializers
from jewelry.models import ProductAttributeHistory, Product


class AttributeHistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductAttributeHistory
        fields = ['key', 'last_value']


# class ProductSerializer(serializers.ModelSerializer):
#     # 自定义字段示例
#     thumbnail_url = serializers.SerializerMethodField()
#     categories = serializers.StringRelatedField(many=True)
#
#     class Meta:
#         model = Product
#         fields = '__all__'  # 包含所有字段
#         depth = 1  # 嵌套序列化关联对象
#
#     def get_thumbnail_url(self, obj):
#         if obj.thumbnail:
#             return self.context['request'].build_absolute_uri(obj.thumbnail.url)
#         return None
#
#     def to_representation(self, instance):
#         """处理Decimal字段等特殊类型"""
#         data = super().to_representation(instance)
#         data['price'] = float(data['price']) if data.get('price') else None
#         return data
class ProductSerializer(serializers.ModelSerializer):
    thumbnail_url = serializers.SerializerMethodField()
    thumbnail = serializers.SerializerMethodField()  # 新增对原始thumbnail字段的处理
    # categories = serializers.StringRelatedField(many=True)
    categories = serializers.SerializerMethodField()  # 改为自定义方法字段
    main_images = serializers.SerializerMethodField()  # 新增主图字段

    class Meta:
        model = Product
        fields = '__all__'
        depth = 1

    def get_categories(self, obj):
        """返回分类的id和name组成的字典列表"""
        return [
            {'id': category.id, 'name': category.name}
            for category in obj.categories.all()
        ]

    def get_thumbnail_url(self, obj):
        """返回完整的绝对URL"""
        if obj.thumbnail:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.thumbnail.url) if request else obj.thumbnail.url
        return None

    def get_thumbnail(self, obj):
        """统一处理原始thumbnail字段"""
        return self.get_thumbnail_url(obj)  # 复用逻辑

    def get_main_images(self, obj):
        """返回所有主图的完整URL"""
        request = self.context.get('request')
        return [
            {
                'id': image.id,
                'src': request.build_absolute_uri(image.image.url) if request else image.image.url,
                'created_at': image.created_at
            }
            for image in obj.main_images.all()
        ]

    def to_representation(self, instance):
        data = super().to_representation(instance)

        # 处理价格字段
        data['price'] = float(data['price']) if data.get('price') else None

        # 处理description中的图片路径
        if 'description' in data and data['description']:
            request = self.context.get('request')
            if request:
                data['description'] = data['description'].replace(
                    'src="/media/',
                    f'src="{request.build_absolute_uri("/media/")}'
                )

        return data
